package com.v9.common.jwt;

import com.v9.common.dto.UserDto;
import com.v9.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JWTAuthorizationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtils tokenUtils;


    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {
        String tokenHeader = getToken(request);
        if (Objects.nonNull(tokenHeader)) {
            String token = getToken(request);
            UserDto redisUser = tokenUtils.getUser(token);
            if (Objects.nonNull(redisUser)) {
                // 验证token有效期
                tokenUtils.verifyToken(redisUser);
                RequestContextHolder.getRequestAttributes().setAttribute("_user", redisUser, RequestAttributes.SCOPE_REQUEST);
            }
        }
        chain.doFilter(request, response);
    }

    protected String getToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            if (request.getCookies() != null) {
                for (Cookie cookie : request.getCookies()) {
                    if (cookie.getName().equals("token")) {
                        return cookie.getValue();
                    }
                }
            }
        }
        return token;
    }
}
